<template>
  <div class="product-list-view">
    <div class="header">
      <h1>商品管理</h1>
      <div>
        <el-button @click="handleManageCategories">分类管理</el-button>
        <el-button type="primary" @click="handleAdd" style="margin-left: 12px;">新增商品</el-button>
      </div>
    </div>

    <el-table :data="products" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="point" label="所需积分"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'success' : 'danger'">
            {{ row.status === 0 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
      class="pagination"
    >
    </el-pagination>

    <ProductForm ref="productFormRef" @success="fetchProducts" />

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductForm from '@/views/admin/product/ProductForm.vue'
import type { Product } from '@/types'
import { getAdminProductList, deleteProduct } from '@/api/modules/product'

const router = useRouter()
const products = ref<Product[]>([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const productFormRef = ref<InstanceType<typeof ProductForm> | null>(null)

const fetchProducts = async () => {
  try {
    loading.value = true
    const response = await getAdminProductList({ page: page.value, size: pageSize.value })
    products.value = response.list
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleManageCategories = () => {
  router.push('/admin/products/categories')
}

const handleAdd = () => {
  productFormRef.value?.open()
}

const handleEdit = (product: Product) => {
  productFormRef.value?.open(product)
}

const handleDelete = (product: Product) => {
  ElMessageBox.confirm(`确定要删除商品 "${product.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteProduct(product.id)
      ElMessage.success('删除成功')
      fetchProducts() // Refresh list
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }).catch(() => {
    // User cancelled
  })
}

const handlePageChange = (currentPage: number) => {
  page.value = currentPage
  fetchProducts()
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
